package com.k2data.etl;

import vcommon.utils.TimeUtils;
import vcommon.utils.httpclient.HttpMethod;
import vcommon.utils.httpclient.HttpsUtil;
import vcommon.utils.httpclient.SimpleHttpResponse;
import com.alibaba.fastjson.JSON;
import jodd.io.FileUtil;
import org.apache.http.Header;
import org.apache.http.client.HttpClient;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BqSime2 {
    private static Map<String, String> authHeader = new HashMap<>();
    private String outDir = "d:/work/";

    public static void main(String[] args) throws Exception {
        BqSime2 sime = new BqSime2();

        List<RequestConf> rcs = getReqs();

        try {

            HttpClient httpClient = HttpsUtil.getHttpClient();
            for (RequestConf rc : rcs) {
                System.out.println(rc.getUrl());

                rc.getHeaders().putAll(authHeader);

                request(httpClient, rc, sime.outDir);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<RequestConf> getReqs() {
        List<RequestConf> rcs = new ArrayList<>();

        RequestConf rc = new RequestConf();
        rc.setUrl("https://10.10.3.113/rs/esm/v2/login");

        rc.setHeaders(new HashMap<>());
        rc.getHeaders().put("Content-Type", "application/json");

        rc.setMethod("POST");

        rc.setBody(new HashMap<>());
        rc.getBody().put("username", "emhpZHU=");
        rc.getBody().put("password", "QmFpY0AxMjM=");
        rc.getBody().put("locale", "en_US");

        rcs.add(rc);

        rc = new RequestConf();
        rc.setUrl("https://10.10.3.113/rs/v1/runningQuery");

        rc.setHeaders(new HashMap<>());
        rc.getHeaders().put("Content-Type", "application/json");
        rc.setMethod("POST");

        rc.setBodyStr("{\"query\":{\"fields\":{},\"sources\":{\"opt\":\"SOURCE\",\"opr\":[],\"exp\":[{\"opt\":\"EQUALS\",\"opr\":[\"QUERYID\",\"32\"],\"exp\":[]},{\"opt\":\"EQUALS\",\"opr\":[\"ESMQUERYTYPE\",\"EVENT\"],\"exp\":[]},{\"opt\":\"EQUALS\",\"opr\":[\"ESMQUERYDEVICESOURCE\",\"Alert.IPSID\"],\"exp\":[]}]},\"filters\":{\"opt\":\"AND\",\"opr\":null,\"exp\":[{\"opt\":\"EQUALS\",\"opr\":[\"Alert.LastTime\",\"$Current,?Day,DV,DV\"],\"exp\":null},{\"opt\":\"EQUALS\",\"opr\":[\"Alert.IPSID\",\"144115188075855872/8\"],\"exp\":null}]},\"groups\":{},\"orders\":{\"opt\":\"ORDER\",\"opr\":null,\"exp\":[{\"opt\":\"DESC\",\"opr\":[\"3\"],\"exp\":null}]}},\"customOptions\":{\"requireTimeFrame\":false},\"queryParameters\":[],\"limit\":20,\"offset\":0,\"reverse\":false,\"getTotal\":true}");

        rcs.add(rc);

        return rcs;
    }

    private static void request(HttpClient httpClient, RequestConf rc, String outDir) {
        try {
            SimpleHttpResponse response = HttpsUtil.request(httpClient, rc.getUrl(), rc.getHeaders(), HttpMethod.valueOf(rc.getMethod()), (rc.getBody() == null || rc.getBody().size() == 0) ? rc.getBodyStr() : JSON.toJSONString(rc.getBody()), null);
            saveResponseToFile(response, outDir);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void saveResponseToFile(SimpleHttpResponse response, String outDir) throws IOException {
        StringBuilder sb = new StringBuilder();

        sb.append(response.getStatusCode()).append("\n");
        sb.append(response.getReason()).append("\n");

        sb.append("\n").append("\n");

        for (Header header : response.getHeaders()) {
            sb.append(header.getName()).append("=").append(header.getValue()).append("\n");
            if ("Set-Cookie".equals(header.getName())) {
                authHeader.put("Cookie", header.getValue());
            }
            if ("Xsrf-Token".equals(header.getName())) {
                authHeader.put("X-Xsrf-Token", header.getValue());
            }
        }

        sb.append("\n").append("\n");

        sb.append(response.getText()).append("\n");

        FileUtil.writeString(new File(outDir + "/" + TimeUtils.now()), sb.toString());
    }

}
